package com.sam.designpatterns;

/**
 * 责任链
 * Created by samwang on 2018/4/21.
 */
public class Responsibility {
    public static void main(String[] args) {
        Handler handler1 = new Handler(1);
        Handler handler2 = new Handler(2);
        Handler handler3 = new Handler(3);
        Handler handler4 = new Handler(4);
        Handler handler5 = new Handler(5);

        Handler finalHandler = new FinalHandler();

        handler1.next = handler2;
        handler2.next = handler3;
        handler3.next = handler4;
        handler4.next = handler5;
        handler5.next = finalHandler;//也可以通过list组成链

        handler1.handleRequest(1);
        handler1.handleRequest(3);
        handler1.handleRequest(100);


    }


    static class Handler {
        Handler next;
        int level;

        public Handler(int level) {
            this.level = level;
        }

        public boolean handleRequest(int i){//可以使用相同的实现
            if (i == level) {
                System.out.println("我的level是 "+level+ ", 我处理"+i+" 这件事");
                return true;
            } else {
                if (next != null) {
                    next.handleRequest(i);
                }
            }
            return false;
        }
    }

    static class FinalHandler extends Handler {//可以扩展出不同的实现

        public FinalHandler() {
            super(Integer.MAX_VALUE);
        }

        @Override
        public boolean handleRequest(int i) {
            System.out.println("传到我这的我都处理了！处理了 "+ i +" 事件");
            return true;
        }
    }
}
